package com.jbt.mds.obdsdk

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.jbt.mds.obdsdk.adapter.VehicleHistoryAdapter
import com.jbt.mds.obdsdk.extension.SPUtils
import com.jbt.mds.obdsdk.model.VehicleHistory
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

class DetectionHistoryFragment : Fragment() {
    private lateinit var adapter: VehicleHistoryAdapter
    private var allList: List<VehicleHistory> = emptyList()
    private var currentPage = 1
    private var pageSize = 10
    private var totalPages = 1
    private var isLoading = false
    private var searchKeyword = ""
    
    // UI组件
    private lateinit var recyclerView: RecyclerView
    private lateinit var etSearch: EditText
    private lateinit var btnSearch: Button
    private lateinit var swipeRefresh: SwipeRefreshLayout
    private lateinit var llLoadingMore: LinearLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_detection_history, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化UI组件
        initViews(view)
        
        // 初始化RecyclerView
        initRecyclerView()
        
        // 设置搜索功能
        setupSearch()
        
        // 设置下拉刷新
        setupSwipeRefresh()
        
        // 设置上拉加载更多
        setupLoadMore()
        
        // 加载第一页数据
        loadData(1, true)
    }
    
    private fun initViews(view: View) {
        recyclerView = view.findViewById(R.id.rv_history)
        etSearch = view.findViewById(R.id.et_search)
        btnSearch = view.findViewById(R.id.btn_search)
        swipeRefresh = view.findViewById(R.id.swipe_refresh)
        llLoadingMore = view.findViewById(R.id.ll_loading_more)
    }
    
    private fun initRecyclerView() {
        adapter = VehicleHistoryAdapter(emptyList()) { jsonString ->
            showFailReasonDialog(jsonString)
        }
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter
    }
    
    private fun setupSearch() {
        btnSearch.setOnClickListener {
            searchKeyword = etSearch.text.toString().trim()
            currentPage = 1
            loadData(1, true)
        }
        
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                // 实时搜索，延迟500ms执行
                Handler(Looper.getMainLooper()).removeCallbacks(searchRunnable)
                Handler(Looper.getMainLooper()).postDelayed(searchRunnable, 500)
            }
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
    }
    
    private val searchRunnable = Runnable {
        searchKeyword = etSearch.text.toString().trim()
        currentPage = 1
        loadData(1, true)
    }
    
    private fun setupSwipeRefresh() {
        swipeRefresh.setColorSchemeResources(android.R.color.holo_blue_bright)
        swipeRefresh.setOnRefreshListener {
            currentPage = 1
            loadData(1, true)
        }
    }
    
    private fun setupLoadMore() {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                
                // 当滚动到倒数第3个item时开始加载更多
                if (!isLoading && currentPage < totalPages && lastVisibleItem >= totalItemCount - 3) {
                    loadMore()
                }
            }
        })
    }

    // 新增弹窗方法
    private fun showFailReasonDialog(jsonString: String) {
        val details = StringBuilder()
        try {
            val jsonObject = JSONObject(jsonString)
            val keys = jsonObject.keys()
            var hasFailure = false
            while (keys.hasNext()) {
                val key = keys.next()
                val itemObject = jsonObject.getJSONObject(key)
                if (itemObject.optInt("code") == 0) { // 假设 code 0 代表不合格
                    details.append("• ${itemObject.optString("msg")}\n\n")
                    hasFailure = true
                }
            }
            if (!hasFailure) {
                details.append("无具体不合格项信息。")
            }
        } catch (e: Exception) {
            details.append("无法解析不合格项详情。")
            e.printStackTrace()
        }

        AlertDialog.Builder(requireContext())
            .setTitle("不合格项详情")
            .setMessage(details.toString())
            .setPositiveButton("确定", null)
            .show()
    }

    private fun loadData(page: Int, isRefresh: Boolean) {
        if (isLoading) return
        
        isLoading = true
        if (isRefresh) {
            swipeRefresh.isRefreshing = true
        } else {
            llLoadingMore.visibility = View.VISIBLE
        }
        
        val client = OkHttpClient.Builder()
            .callTimeout(1, TimeUnit.DAYS)
            .readTimeout(1, TimeUnit.DAYS)
            .writeTimeout(1, TimeUnit.DAYS)
            .build()

        // 构建URL，包含搜索参数
        val url = buildUrl(page)
        val request = Request.Builder()
            .url(url)
            .get()
            .addHeader("Authorization", "Bearer " + SPUtils.getString("token", ""))
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                requireActivity().runOnUiThread {
                    isLoading = false
                    swipeRefresh.isRefreshing = false
                    llLoadingMore.visibility = View.GONE
                    Toast.makeText(requireContext(), "网络请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string() ?: return
                val json = JSONObject(responseBody)
                Log.i("DetectionHistory", "Response: $json")
                
                val data = json.optJSONObject("data")
                val rows = data?.optJSONArray("rows") ?: return
                val total = data.optInt("total", 0)
                totalPages = (total + pageSize - 1) / pageSize // 计算总页数
                
                val list = ArrayList<VehicleHistory>()
                for (i in 0 until rows.length()) {
                    val obj = rows.getJSONObject(i)
                    val plate = obj.optString("license")
                    val vin = obj.optString("vin")
                    val time = obj.optString("createTime").replace("T", " ").replace("Z", "")
                    val vehicleType = obj.optString("type")
                    val status = when (obj.optInt("resultStatus")) {
                        0 -> "不合格"
                        1 -> "合格"
                        2 -> "疑似篡改"
                        else -> "未知状态"
                    }
                    val executeResult = obj.optString("executeResult", "{}")
                    list.add(VehicleHistory(plate, vin, time, vehicleType, status, executeResult))
                }
                
                requireActivity().runOnUiThread {
                    isLoading = false
                    swipeRefresh.isRefreshing = false
                    llLoadingMore.visibility = View.GONE
                    
                    if (isRefresh) {
                        allList = list
                        adapter.updateData(list)
                    } else {
                        // 加载更多，追加数据
                        val newList = allList.toMutableList()
                        newList.addAll(list)
                        allList = newList
                        adapter.updateData(allList)
                    }
                    
                    currentPage = page
                }
            }
        })
    }
    
    private fun buildUrl(page: Int): String {
        val baseUrl = "http://115.153.96.26:10061/calculation-results"
        val urlBuilder = StringBuilder("$baseUrl?page=$page&pageSize=$pageSize")
        
        // 如果有搜索关键词，添加到URL中
        if (searchKeyword.isNotEmpty()) {
            urlBuilder.append("&license=").append(searchKeyword)
        }
        
        return urlBuilder.toString()
    }
    
    private fun loadMore() {
        if (currentPage < totalPages && !isLoading) {
            loadData(currentPage + 1, false)
        }
    }
}
